import communication from "../utils/communication";
import { useRoute } from "vue-router";
import {
  EVENT_CONFIG_MSG,
  EVENT_INTI_CONFIG,
  EVETN_CONTROL_CONFIG_MSG,
  EVENT_SCREEN_TO_CONFG,
  EVENT_LEAVE_PAGE,
  EVENT_ENTER_PAGE,
} from "../utils/constant";
import defaultConfig from "../../config";
import { onDeactivated, onUnmounted, ref, reactive, onActivated, shallowRef, inject, effect, onMounted } from "vue";

export default function useClient(isControl = false) {
  const route = useRoute();
  let client = null;
  /**
   * 连接类型
   */
  const commType = ref(null);
  /**
   * 视图配置
   */
  const viewConfig = reactive(defaultConfig);
  /**
   * 当前设备名称
   */
  const username = ref("");
  /**
   * 正在等待设备连接
   */
  const loading = ref(true);

  /**
   * 收集到的当前用户在线信息
   */
  const viewUserNames = ref([]);

  const screenOptions = ref([]);

  const screenSrc = `${location.protocol}//${location.host}/#/fangying/${route.params.id}`;

  /**
   * 屏幕信息
   */
  const screenInfo = shallowRef(null);
  // init();

  function init() {
    console.log("init");
    communication.init(route.params.id, { isControl: isControl }).then((_client) => {
      client = _client;
      commType.value = _client.clientName;
      username.value = client.username;
      loading.value = false;
      if (!isControl) {
        client.on(EVENT_CONFIG_MSG, ({ config }) => {
          console.log("收到配置消息了！", config);
          setViewConfig(config);
        });
      }

      if (isControl) {
        client.on(EVENT_INTI_CONFIG, ({ config }) => {
          console.log("初始化配置消息", config.pageIndex);
          config.isPlayAudio = false;
          setViewConfig(config);
          sendConfig(config);
        });

        client.on(EVETN_CONTROL_CONFIG_MSG, ({ config }) => {
          setViewConfig(config);
        });

        client.on(EVENT_SCREEN_TO_CONFG, ({ config }) => {
          console.log("收到屏幕配置消息", config);
          screenInfo.value = config;
        });
      }

      client.on(EVENT_LEAVE_PAGE, (data, userNames) => {
        console.log("用户离开页面事件类型", data, userNames);
        viewUserNames.value = userNames;
      });

      client.on(EVENT_ENTER_PAGE, (data, userNames) => {
        console.log("用户进入页面事件类型", data, userNames);
        viewUserNames.value = userNames;
      });
    });
  }

  function sendConfig(config) {
    if (isControl) {
      client?.doPublishConfig(config);
    }
  }

  function setViewConfig(data) {
    if (!data) {
      return;
    }
    for (let key in data) {
      viewConfig[key] = data[key];
    }
  }

  onMounted(() => {
    console.log("on mounted");
    init();
  });

  onUnmounted(() => {
    console.log("on onUnmounted");
    communication?.destroy();
  });

  return {
    sendConfig,
    commType,
    viewConfig,
    username,
    loading,
    viewUserNames,
    screenSrc,
    screenInfo,
    clientId: route.params.id,
  };
}
